package com.kaibes.module.security.api;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.kaibes.module.security.entity.Authority;
import com.kaibes.module.security.service.AuthorityService;
import com.kaibes.web.api.ApiLink;
import com.kaibes.web.api.ResponseApi;
import com.kaibes.web.response.BooleanResult;
import com.kaibes.web.response.ResponseFactory;

@RestController
@RequestMapping("/authoritis")
public class AuthorityApi extends ResponseApi<Authority, AuthorityService> {
	
	@Autowired
	private AuthorityService authorityService;
	
	@ApiLink(value = "查询权限列表", validated = false)
    @GetMapping
    public ResponseEntity<List<Authority>> get() {
        return ResponseFactory.get(authorityService.list(), "查询权限成功", "查询权限失败");
    }
	
	@ApiLink(value = "增加权限列表", validated = false)
	@PostMapping
	public ResponseEntity<List<Authority>> post(@RequestBody List<Authority> authorityDatas) {
	    List<Authority> dataList = new ArrayList<>();
	    for (Authority authorityData : authorityDatas) {
            if (authorityService.notName(authorityData.getName())) {
                dataList.add(authorityData);
            }
        }
	    authorityService.save(dataList);
		return ResponseFactory.postSuccess("新增权限成功");
	}
	
	@ApiLink(value = "根据角色ID查询权限列表", validated = false)
	@GetMapping("/{roleId:\\d+}")
	public ResponseEntity<List<Authority>> getByRoleId(@PathVariable Integer roleId) {
	    List<Authority> authorities = authorityService.listByRoleId(roleId);
	    return ResponseFactory.get(authorities, "获取权限成功", "获取权限列表失败");
    }
	
	@ApiLink(value = "根据角色ID查询是否有权限", validated = false)
	@GetMapping("/has/{roleId:\\d+}")
	public ResponseEntity<BooleanResult> checkByRoleId(@PathVariable Integer roleId, @RequestParam String authority) {
	    List<Authority> authorities = authorityService.listByRoleId(roleId);
        for (Authority temp : authorities) {
            if (authority.equals(temp.getName())) {
                return ResponseFactory.get(new BooleanResult(true));
            }
        }
	    return ResponseFactory.get(new BooleanResult(false));
	}
	
}
